/** ***********************************************
 * CodeGen
 *
 * @author  Jonnie Spratley
 * @date 3/05/2009
 * @licence MCIYC
 * @website http://jonniespratley.com/code
 * @contact jonniespratley@gmail.com
 *********************************************** */
package com.jonniespratley.codegen.commands
{
	import com.adobe.cairngorm.commands.ICommand;
	import com.adobe.cairngorm.control.CairngormEvent;
	import com.adobe.serialization.json.JSON;
	import com.jonniespratley.codegen.business.CodeGenDelegate;
	import com.jonniespratley.codegen.events.GetDatabasesEvent;
	import com.jonniespratley.codegen.model.ModelLocator;
	import com.jonniespratley.codegen.vo.*;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.IResponder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.utils.ObjectUtil;

	/**
	 * For every feature or use case in your application, a corresponding custom command
	 * and event must be created. Each command contains an execute() method that is run
	 * by the framework when the user action has been executed.
	 * These classes are occasionally referred to as worker classes because they carry
	 * out the work for an application.
	 *
	 */
	public class GetDatabasesCommand implements ICommand, IResponder
	{
		private var model:ModelLocator = ModelLocator.getInstance();

		public function execute( event:CairngormEvent ) : void
		{
			var evt:GetDatabasesEvent = event as GetDatabasesEvent;
			var delegate:CodeGenDelegate = new CodeGenDelegate( this );
				delegate.getDatabases( evt.aHost, evt.aUser, evt.aPass );

		}

		public function result( data:Object ) : void
		{
			var event:ResultEvent = data as ResultEvent;
			if ( event.result is String )
			{
				var rawData:String = String( event.result );
				var jsonArray:Array = ( JSON.decode( rawData ) as Array );
				var tempAC:ArrayCollection = new ArrayCollection( /* jsonArray */ );

				 if ( model.databaseCollection == null )
				{
					  for(var s:String in jsonArray ){
					 	tempAC.addItem( new Database( jsonArray[ s ] ) );
					 } 
					model.databaseCollection = tempAC;
				} 
			}
			/* var bracketPattern:RegExp = /(\[)/gim;
			var commaPattern:RegExp = /(,)/gim; */
			model.applicationDump += ObjectUtil.toString( event.result );
			/* model.applicationDump.replace( bracketPattern, '\n\t[' ).replace( commaPattern, '\n\t\t' ); */
		}

		public function fault( fault:Object ):void
		{
			var faultEvt:FaultEvent = fault as FaultEvent;
 
			trace(faultEvt.fault.faultString);
		}

	}
}
